package system

import (
	"context"
	"regexp"
	"strconv"
	"time"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"
	"portal/tools/encryption"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddUserLogic struct {
	logx.Logger
	ctx       context.Context
	svcCtx    *svc.ServiceContext
	userModel model.SysUserModel
	menuModel model.SysMenuModel
}

func NewAddUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddUserLogic {
	return &AddUserLogic{
		Logger:    logx.WithContext(ctx),
		ctx:       ctx,
		svcCtx:    svcCtx,
		userModel: model.NewSysUserModel(svcCtx.Orm),
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
	}
}

func (l *AddUserLogic) AddUser(req *types.AddUserRequest) (resp *types.CommonResponse, err error) {
	err = auth.HasPermission(l.menuModel, l.ctx, "system:user:add")
	if err != nil {
		return nil, errorx.Unauthorized
	}
	// 权限判断
	userinfo, err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil, err
	}

	user := &model.SysUser{}
	if len(req.DeptId) != 0 {
		deptId, err := strconv.Atoi(req.DeptId)
		if err != nil {
			return nil, err
		}
		user.DeptId.Int64 = int64(deptId)
		user.DeptId.Valid = true
	}
	if len(req.Avatar) > 0 {
		user.Avatar = req.Avatar
	}
	if len(req.Sex) > 0 {
		user.Sex = req.Sex
	}
	if len(req.Email) > 0 {
		reg := regexp.MustCompile(common.EmailFormat)
		if !reg.MatchString(req.Email) {
			return nil, errorx.NewBizError(500, "邮箱格式不正确")
		}
		user.Email = req.Email
	}
	if len(req.Password) <= 0 {
		return nil,errorx.NewBizError(500,"用户密码不能为空")
	}
	reg := regexp.MustCompile(common.PasswordFormat)
	if !reg.MatchString(req.Password) {
		return nil, errorx.NewBizError(500, "密码格式不正确")
	}
	pwd, err := encryption.EncryptionMd5(req.Password, l.svcCtx.Config.Salt)
	if err != nil {
		return nil, err
	}
	user.Password = pwd
	user.PwdUpdateDate = time.Now().Unix()
	if len(req.Phonenumber) > 0 {
		reg := regexp.MustCompile(common.PhoneFormat)
		if !reg.MatchString(req.Phonenumber) {
			return nil, errorx.NewBizError(500, "手机号码格式不正确")
		}
		user.Phonenumber = req.Phonenumber
	}
	if len(req.NickName) <= 0 {
		return nil,errorx.NewBizError(500,"用户昵称不能为空")
	}
	user.NickName = req.NickName
	if len(req.UserName) <= 0 {
		return nil,errorx.NewBizError(500,"用户名不能为空")
	}
	reg = regexp.MustCompile(common.UserFormat)
	if !reg.MatchString(req.UserName) {
		return nil, errorx.NewBizError(500, "用户名格式不正确")
	}
	if req.UserType != common.SYSTEM_UT {
		return nil,errorx.ParamsError
	}
	user.DelFlag = common.EXIST_FLAG
	user.UserType = common.SYSTEM_UT
	user.UserName = req.UserName
	user.CreateBy = userinfo.UserName
	user.CreateTime = time.Now().Unix()
	user.UpdateTime = time.Now().Unix()
	user.UpdateBy = userinfo.UserName
	userdto, err := l.userModel.GetOneByUserName(l.ctx, nil, req.UserName)
	if err == nil || userdto.DelFlag == "0" {
		return nil, errorx.NewBizError(500, "用户名已存在")
	}
	err = oprUserRelations(l.userModel, l.ctx, req.UserId, req.PostIds, req.RoleIds, common.OPR_INSERT)
	if err != nil {
		return nil, err
	}
	user.Status = req.Status
	userId, err := l.userModel.InsertGetId(l.ctx,nil, user)
	if err != nil {
		return nil,errorx.SqlInsertError
	}
	return &types.CommonResponse{
		Status: 200,
		Msg:    "修改成功",
		Data: types.IdResponse{
			Id: userId,
		},
	}, err
}
